package com.sharding.utils.anno;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.text.SimpleDateFormat;

/**
 * Desc:
 * Date:    2023/2/27
 *
 * @author WanYangWei
 */
public class DateTimeFormatCheck implements ConstraintValidator<DateTimeFormat, String> {

    private static final Logger logger = (Logger) LoggerFactory.getLogger(DateTimeFormatCheck.class);
    private static final String dateTimePattern = "yyyy-MM-dd HH:mm:ss";
    private static final SimpleDateFormat dateTimeFormat = new SimpleDateFormat(dateTimePattern);

    private boolean required;

    @Override
    public void initialize(DateTimeFormat cons) {
        required = cons.required();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        boolean result = true;
        if (required) {
            if (StringUtils.isNotBlank(value)) {
                try {
                    dateTimeFormat.parse(value);
                } catch (Exception e) {
                    logger.error("字段:{}格式不符合:{}的格式,请检查!", value, dateTimePattern);
                    result = false;
                }
            } else {
                result = false;
            }
        }
        return result;
    }
}
